##########################################
#			setup.s by doom119			 #
#				April, 2010				 #
##########################################

.code16
.equ SETUPSEG,0X9020
.equ SYSSEG, 0x1000
.equ INITSEG, 0x9000
.text
.global _setup
_setup:
/*get current cursor position and save it to 0x90000*/
	mov $INITSEG, %ax
	mov %ax, %ds
	mov $3, %ah
	xor %bh, %bh
	int $0x10
	mov %dx, (0)

/*get extended memory size(KB)*/
	mov $0x88, %ah
	int $0x15
	mov %ax, (2)

/*get video card data(nowdays the video card may be different, scoured it)*/
#save display page to 0x90004, display mode to 0x90006, columns to 0x90007
	mov $0x0f, %ah
	int $0x10
	mov %bx, (4)
	mov %ax, (6)

/*check for EGA/VGA and some config parameters(ds:8 aborted)*/
	mov $0x12, %ah
	mov $0x10, %bl
	int $0x10
	mov %bx, (10)
	mov %cx, (12)

/*copy hd0 data to 0x90080*/
	mov $0, %ax
	mov %ax, %ds
	mov $4*0x41, %si
	mov $INITSEG, %ax
	mov %ax, %es
	mov $0x80, %di
	mov $8, %cx
	rep
	movsw

/*at present, ignoring hd1 even though exists*/


/*to jump into protected mode*/
	cli
	cld

#move system to 0x0
	mov $0, %ax
1:
	mov %ax, %es
	add $0x1000, %ax
	cmp $0x9000, %ax
	je 2f
	mov %ax, %ds
	xor %si, %si
	xor %di, %di
	mov $0x8000, %cx
	rep
	movsw
	jmp 1b

#load gdt
2:
	mov $SETUPSEG, %ax
	mov %ax, %ds
	lgdt (_gdt_48)

#enable A20
//is this OK?
	in $0x92, %al
	or $2, %al
	out %al, $0x92

#reprogram 8259A, move their interupts to 0x20-0x2F
	mov $0x11, %al
	out %al, $0x20
	.word 0x00eb, 0x00eb
	out %al, $0xA0
	.word 0x00eb, 0x00eb

	mov $0x20, %al
	out %al, $0x21
	.word 0x00eb, 0x00eb
	mov $0x28, %al
	out %al, $0xA1
	.word 0x00eb, 0x00eb

	mov $4, %al
	out %al, $0x21
	.word 0x00eb, 0x00eb
	mov $2, %al
	out %al, $0xA1
	.word 0x00eb, 0x00eb

	mov $3, %al
	out %al, $0x21
	.word 0x00eb, 0x00eb
	out %al, $0xA1
	.word 0x00eb, 0x00eb

	mov $0xFF, %al
	out %al, $0x21
	.word 0x00eb, 0x00eb
	out %al, $0xA1

#set PE bit
	movl %cr0, %eax
	orl $1, %eax
	movl %eax, %cr0

	jmpl $8, $0

test:
	.ascii "ok"

_gdt:
	.quad 0

	.word 0x07ff
	.word 0x0000
	.word 0x9a00
	.word 0x00c0

	.word 0x07ff
	.word 0x0000
	.word 0x9200
	.word 0x00c0
_gdt_48:
	.word 0x800
	.word _gdt+512, 9

